let groupId_userId
if (localStorage.getItem('user')) {
    console.log('我进来了');
    groupId_userId = sessionStorage.getItem('groupId') + "-" + JSON.parse(localStorage.getItem('user')).id
}
let wsurl = `ws://zyl310.cn:8080/websocket/${groupId_userId}`
console.log(wsurl);
let ws = null
let weboscket_callback = null

//获取 websocket 推送的数据
let websocketonmessage = e => {
    return weboscket_callback(e)
}

// 连接成功
let websocketonopen = () => {
    console.log('连接 websocket 成功')
}

// 连接失败时重新连接
let websocketonerror = () => {
    initWebSocket()
}

// 断开链接后报错
let websocketclose = e => {
    console.log('断开连接', e)
}

// 手动关闭 websocket
let closewebsocket = () => {
    ws.close()
}

let initWebSocket = () => {
    //初始化 websocket
    ws = new WebSocket(wsurl)
    ws.onmessage = websocketonmessage
    ws.onopen = websocketonopen
    ws.onerror = websocketonerror
    ws.onclose = websocketclose
}

// 发送数据
let sendData = (data, callback) => {
    weboscket_callback = callback

    //  判断 websocket 的状态
    if (ws.readyState === ws.OPEN) {
        // 已经打开,可以直接发送
        console.log('已经打开,可以直接发送', data);
        ws.send(data)
        console.log('发送完毕');
    } else if (ws.readyState === ws.CONNECTING) {
        // 正在开启状态中,则 1 秒后重新发送
        setTimeout(() => {
            ws.send(data)
        }, 1000)
    } else {
        // 未打开，则开启后重新调用
        initWebSocket()
        sendData(data)
    }
}

// 导出
export { initWebSocket, sendData, closewebsocket, websocketonmessage }

// // 用来接收 websocket 推送的数据
// async test() {
//     await this.getGroupMsg()
// },
// // 发送数据
// send(textarea) {
//     let obj = {}
//     obj.groupId = parseInt(sessionStorage.getItem('groupId'))
//     obj.userId = this.myMsg.id
//     obj.userMsg = textarea
//     obj.sendTime = new Date()
//     let data = JSON.stringify(obj)
//     sendData(data, this.test)
//     //让每次发送消息都显示在
//     var ChatContent = document.querySelector('.chat_content')
//     ChatContent.scrollTop = ChatContent.scrollHeight;
//     this.textarea = ''
// },
// close() {
//     closewebsocket()
// }
//     },
// created() {
//     this.getGroupMember()
//     this.getGroupMsg()
//     initWebSocket()
// },
// destroyed() {
//     this.close()
// },

